package com.ldy.core.common;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.ldy.core.entity.BaseAuditLog;
import com.ldy.core.entity.BaseUser;
import com.ldy.core.service.BaseAuditLogService;
import com.ldy.core.util.IpUtil;
import com.ldy.core.util.MySession;

/**
 * 审计日志拦截器
 */
@Component
public class AuditLogInterceptor implements HandlerInterceptor {

	private static final Logger logger = LoggerFactory.getLogger(AuditLogInterceptor.class);

	@Autowired
	private BaseAuditLogService auditLogService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 获取用户名（这里假设通过SecurityContextHolder获取，需要根据你的应用实际情况修改）
		try {
			String username = "";
			// 使用Spring Security获取当前用户（如果使用了Spring Security）
			BaseUser user = MySession.get();
			if (user != null) {
				username = user.getNickname();
			}
			// 获取客户端IP地址
			String clientIp = IpUtil.getClientIp(request);

			// 创建审计日志对象
			BaseAuditLog auditLog = new BaseAuditLog();
			auditLog.setUsername(username);
			auditLog.setRequestUri(request.getRequestURI());
			auditLog.setHttpMethod(request.getMethod());
			auditLog.setClientIp(clientIp);
			auditLog.setCreateTime(new Date());

			// 保存审计日志
			auditLogService.save(auditLog);
		} catch (Exception e) {
			logger.error("", e);
		}
		return true; // 继续处理请求
	}
}